package com.ale.oxetool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;

import java.util.List;


@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    private static Logger log = LoggerFactory.getLogger(WebServiceConfig.class);

//    @Autowired
//    private CustomEndpointInterceptor ceInterceptor;

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
//        https://memorynotfound.com/spring-ws-intercept-request-response-soap-messages/
        // add interceptor
        // register global interceptor

//        disable this alter soap message interceptor until the customer really need it.
//        interceptors.add(ceInterceptor);
    }

    /**
     * By default, the default wsdl would generate wsdl with schema switchPhoneSchema, but we can use custom wsdl file
     * */

    @Bean(name = "phoneswitch")
    public Wsdl11Definition defaultWsdl11Definition() {
        SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
        wsdl11Definition.setWsdl(new ClassPathResource("/wsdl/phoneswitch.wsdl"));
        return wsdl11Definition;
    }

//    @Bean(name = "phoneswitch")
//    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema switchPhoneSchema) {
//        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
//
//        wsdl11Definition.setPortTypeName("PhoneSwitchPort");
//        wsdl11Definition.setLocationUri("/ws");
//        wsdl11Definition.setTargetNamespace(PhoneSwitchEndPoint.NAMESPACE_URI);
//        wsdl11Definition.setSchema(switchPhoneSchema);
//     return wsdl11Definition;
//    }

    @Bean
    public XsdSchema switchPhoneSchema() {
        return new SimpleXsdSchema(new ClassPathResource("xsd/phoneswitch.xsd"));
    }
}
